package com.ruoyi.framework.listener;

import com.ruoyi.system.domain.Listen;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.file.*;

/**
 * @Description:
 * @Author:let_free
 * @Date:2024/11/25/13:35
 **/
@Component
public class WatchServiceHandler {
//    private final Path pathToWatch = Paths.get("your_directory_path"); // 替换为实际的目录路径

//    绑定监听的目录
    @Autowired
    private Listen listen;

    // 使用 @PostConstruct 确保在类构造后立即启动监听器
//    @PostConstruct
//    public void init() {
//        startWatching();
//    }

    private void startWatching() {
        Path pathToWatch = Paths.get(listen.getPath());
        try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
            pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

            System.out.println("开始监听文件: " + pathToWatch);

            WatchKey key;

            while ((key = watchService.take()) != null) {
                for (WatchEvent<?> event : key.pollEvents()) {
                    WatchEvent.Kind<?> kind = event.kind();
                    Path fileName = (Path) event.context();

                    // 处理文件创建事件
                    if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                        System.out.println("文件创建: " + fileName);
//                        saveFileRecord(fileName);
                    }
                }
                key.reset(); // 重置键以便获取下一个事件
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

}
